#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 80


/* function declaration */

void print_menu();
void callwordfind();
void wordfind(char*, int);
void callletterfind();
int letterfind(char*, int);
void callstringswap();
void swapstr(char*, char* ,int);

/* main function */

int main(){
	int key, cont = 1;
	print_menu();
	while  (cont != 0){
		scanf("%d", &key);
		switch (key){
			case 1:{
				system("cls");
				callwordfind();
				print_menu();
				break;
				   }

			case 2:{
				system("cls");
				callletterfind();
				print_menu();
				break;
				   }
			case 3:{
				system("cls");
				callstringswap();
				print_menu();
				break;
				   }
			default:{
				system("cls");
				return 0;
					}
		}
	}
}
void print_menu(){
	printf("Welcome to Exercise \n");
	printf("1- Word finder by letter \n");
	printf("2- Letter finder\n");
	printf("3- Swap Strings\n");
	printf("0- Exit\n");
}
void callwordfind(){
   char inputstr [SIZE], letter;
   printf("Enter string:\n");
   fflush(stdin);
   gets(inputstr);
   printf("Enter letter:\n\n");
   fflush(stdin);
   letter = getchar();
   wordfind(inputstr, strlen(inputstr), letter);
}
void wordfind(char* str, int size, char letter){
	int i, j, whitespace = 0;
	for(i = 0; i < size; i++){
		if(tolower(str[i]) == tolower(letter) && whitespace == 0){
			j = i;
			while(str[j] != ' '){
				printf("%c", str[j]);
				j++;
			}
			printf("\n");
		}
		if(str[i] == ' '){
			whitespace =0;
		}
		else{
			whitespace =1;
		}
	}
}
void callletterfind(){
	char inputstr [SIZE], letter;
	printf("Enter string:\n");
	fflush(stdin);
	gets(inputstr);
	printf("Enter letter:\n\n");
	fflush(stdin);
	letter = getchar();
	printf("The functions returns: %d\n", letterfind(inputstr, strlen(inputstr), letter));
}
int letterfind(char* str, int size, char letter){
	int i, index = -1;
	for(i = 0; i < size; i++){
		if(tolower(str[i]) == tolower(letter)){
			index = i;
		}
	}
	return index;
}
void callstringswap(){
	char str1 [SIZE], str2[SIZE];
	printf("Enter first string:\n");
	fflush(stdin);
	gets(str1);
	printf("Enter second string:\n\n");
	fflush(stdin);
	gets(str2);
	printf("First string: %s\nSecond string: %s\n", str1, str2);
	printf("Calling swap function...\n\n");
	swapstr(str1, str2, strlen(str1));
	printf("First string: %s\nSecond string: %s\n\n", str1, str2);
}
void swapstr(char* str1, char* str2, int size){
	int i;
	char temp;
	for(i = 0; i < size; i++){
		temp = str1[i];
		str1[i] = str2[i];
		str2[i] = temp;
	}
}